# -*- coding:utf-8 -*-
__author__ = 'gxb'
import time,datetime
import urllib
import urlparse
from pyquery import PyQuery as pq
from DbUtile import *
import re
import codecs
import os

def encodeUrl(base_url,encodeUrl):
    url = encodeUrl
    url = url.encode('gbk')
    url = urlparse.urlparse(url)
    url_params = urlparse.parse_qsl(url.query)
    encodeUrl = base_url + url.path+ '?' + urllib.urlencode(url_params)
    return encodeUrl

def findTopicHref(html,mpId):

    jqueryObj = pq(html)
    #表格第1行的第4列
    completeText = u'完成'
    splitText = u'课'
    refA = jqueryObj('#report1  a:contains("%s")' % completeText)
    lenA = refA.length

    with db.transaction():
        if(lenA>0):

            for i in range(0,lenA) :
                topicUrl = refA.eq(i).attr('href')
                topicUrl = encodeUrl('',topicUrl)
                topicName = refA.eq(i).text().split(splitText)[0]
                db.update('INSERT INTO `history_topic_record` ( `MP_ID`, `TOPIC_NAME`, `TOPIC_URL`, `COMPLETE`)'
                  ' VALUES ( ?,?,?,?)',mpId,topicName,topicUrl,0)

        updateMpRecordComp(mpId)


def getGroupStuLength(html):
    jqueryObj = pq(html)
    #前7行，和最后一行是无用的
    tableLength = jqueryObj('#report1 tr').length-8
    return tableLength


def getName(html,trNum):
    # with open(fileName,'r') as f:
    #     html = f.read()
    jqueryObj = pq(html)
    num = 7+trNum;
    tdLengh = jqueryObj('#report1 tr:eq(%s) td'% num).length
    tdLengh = int(tdLengh)
    trainTime = 0
    #没有合并单元格的有14个td，合并第1行有10格，它后面的只有4格；
    if(tdLengh>10):
        trainTime = jqueryObj('#report1 tr:eq(%s) td:eq(9)' % num).text()
        if(len(trainTime)==0):
            trainTime = 0
        else:
            trainTime = int(trainTime)
    elif(tdLengh==10):
        trainTime = jqueryObj('#report1 tr:eq(%s) td:eq(5)' % num).text()
        if(len(trainTime)==0):
            trainTime = 0
        else:
            trainTime = int(trainTime)
    else:
        trainTime = 0
    get_mp_url = jqueryObj('#report1 tr:eq(%s)' % num).find('a').attr('href')
    # 2,1姓名 1，1,1身份证
    url = urlparse.urlparse(get_mp_url.encode('gbk'))
    # 2,1姓名 1，1,1身份证
    url_params = urlparse.parse_qsl(url.query)
    name = url_params[2][1].decode('gbk')
    id_card = url_params[1][1].decode('gbk')
    #分院是不变的
    college_name = jqueryObj('#report1 tr:eq(%s) td:eq(3)' % 7).text()
    return name,id_card,college_name,trainTime,get_mp_url


def findDate(tpId,tpName,groupId,idCard,html):
    # with open(fileName,'r') as f:
    #     html = f.read()
    jqueryObj = pq(html)
    yearText = u'年'
    #表格最后1行的第12列
    date = jqueryObj('table tr:last td:contains("%s")' % yearText).text()
    date = changeStr2Time(date)
    # filePath = str(tpId)+'dadui'+str(groupId)+'_'+idCard+'_'+tpName+'.html'
    filePath = os.path.join('histroy_record_file','dadui'+str(groupId),idCard)
    print filePath
    if not os.path.exists(filePath):
        os.makedirs(filePath)

    filePath = os.path.join(filePath,str(tpId)+tpName+'.html')
    httpPath = 'histroy_record_file/dadui'+str(groupId)+'/'+idCard+'/'+str(tpId)+tpName+'.html'
    db.update('update `history_topic_record` set rec_time = ? ,file_path = ? ,COMPLETE = ? where id = ?',
              date,httpPath,1,tpId)
    htmlDocType = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
    htmlMeta = '<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>'
    htmlStyle = jqueryObj('#report1_style').outer_html()
    htmlTalbe = jqueryObj('#report1').outer_html()
    htmlNew = '%s <html> %s %s %s </html>'%(htmlDocType,htmlMeta,htmlStyle,htmlTalbe)


    f=codecs.open(filePath,"w","utf-8")
    f.write(htmlNew)
    f.close()
    # with open('histroy_record_file/'+filePath, 'w') as f:
    #     f.write(html)
    return date

def changeStr2Time(strTime):
    text = strTime
    pat = r'\d+'
    results = re.findall(pat,text)
    print 'data:%s' % results
    year,month,day = results
    #str to date
    t = time.strptime(year+'-'+month+'-'+day, "%Y-%m-%d")
    return t
def getGroup(htmlStr):
    htmlLocation = htmlStr.split('"')[1]
    return htmlLocation

def getCurrentTime():
    #获得当前时间
    now = datetime.datetime.now()  #这是时间数组格式
    #转换为指定的格式:
    otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
    return otherStyleTime

    # for l in list:
    #     print group[str(l)]


# url = u'/reportJsp/A_XLJLLR01.jsp?raq=/A2_XLJLLL2.raq&ZZH=500222199306295912&XM=桂焕前&JXM=分院或者大队进行记录监控&JID=分院或者大队进行记录监控&SUserID=22421&KCDM=10001&FX=3'
# url = url.encode('gbk')
# print encodeUrl('http://218.6.160.238:6011',url
# )
# print getMpHref('')
# print getName('tmp.html')
# print  findDate('test.html')
# print changeStr2Time('2015年05月14日') histroy_record_file/
# print getGroup('<script language=javascript>document.location = "http://218.6.160.238:6011/reportJsp/showReport3in.jsp?raq=%2FA2_XLJLFYLL.raq&reportParamsId=137005";</script>')

# filePath = 'dadu1_500222199306295912_FTD1.html'
# with open(os.path.join('histroy_record_file',filePath)) as f:
#    html = f.read()
# jq = pq(html)
# print jq('#report1_style')
# f.close()

# groupId =1
# idCard = 'sss'
# filePath = os.path.join('histroy_record_file','dadui'+str(groupId),idCard)
# print filePath
# if not os.path.exists(filePath):
#     os.makedirs(filePath)